package org.qdao.implement.mysql;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;

import org.qdao.DBConfig;
import org.qdao.DBEngineFactory;
import org.qdao.core.DBType;

import com.tan.util.InitTables;
import com.tan.util.TanUtil;

/**
 * 
 * @author 譚元吉
 * @since 2010-2-27 上午01:43:29
 */
public class MySqlDBEngine extends org.qdao.AbstractDBEngine {

	static {
		DBEngineFactory.register(new MySqlDBEngine());
	}
	protected MySqlDBEngine() {
	}

	public boolean support(DBConfig config) {
		for (String path : config.jarPath) {
			String t = path.toLowerCase();
			if (!t.endsWith(".jar") && !t.endsWith(".class")) {
				return false;
			}
		}
		if (isEmpty(config.driver)
				|| isEmpty(config.username)
				|| isEmpty(config.password)
				|| isEmpty(config.url)) {
			return false;
		}
		int type = DBType.getType(config.driver);
		if (type != DBType.DB_TYPE_MYSQL) {
			return false;
		}
		if (!DBType.supportUrl(type, config.url)) {
			return false;
		}
		
		this.config = config;
		return true;
	}

	private boolean isEmpty(String value) {
		if (value == null || value.trim().length() == 0) {
			return true;
		}
		return false;
	}

	@Override
	public void dispose() {
		super.dispose();
	}

    @Override
    public Connection getConnection() throws SQLException, InstantiationException, IllegalAccessException, ClassNotFoundException
    {
        Connection conn = null;
        try{
            conn = super.getConnection();
        } catch (Throwable e) {
			String message = e.getMessage();
			if ( null != message ){
				message = message.toLowerCase();
				// if unknown database, create the database.
				if (    this.config.isAutoCreateSchema() // 是否自动创建不存在的数据库
						&& message.indexOf("unknown database") >= 0 ) {
					String oldUrl = this.config.url;
					int idx = oldUrl.lastIndexOf('/');
					String mysqlUrl = oldUrl.substring(0, idx);
					String schema = this.config.getSchema();
					System.out.println("数据库" + schema + "不存在!");
					createSchema(mysqlUrl + "/mysql", schema);
					System.out.println("创建数据库:" + schema + "成功 !");
					this.config.url = oldUrl;
					conn = super.getConnection();
					System.out.println("重新连接成功 !");
					if (this.config.isAutoDDL()) { // 是否自动创建数据库表.
						InitTables init = new InitTables();
						if (init.hadNotExistInDatabase()) {
							init.createTables();
						}
						init.destory();
						init = null;
					}
				} else if ( message.indexOf( "communications link failure" ) >=  0 ) {
					// start mysql.
					TanUtil.startMysql();
					return getConnection();
				} else {
					e.printStackTrace();
				}
			}
		}
        return conn;
    }

    private void createSchema(final  String mysqlUrl, final String schema)
    {
		this.config.url = mysqlUrl;
		Connection conn = null;
		Statement stmt = null;
		final String command = "CREATE DATABASE `" + schema
		+ "`CHARACTER SET utf8 COLLATE utf8_unicode_ci";
		try {
			conn = super.getConnection();
			stmt = conn.createStatement();
			System.out.println( command );
			stmt.execute( command );
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} finally {
			if (null != conn)
				try {
					conn.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			if (null != stmt)
				try {
					stmt.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
		}
	}

}
